<?php

    /**
     * Created by PhpStorm.
     * User: HaiXin.Sun
     * Date: 16/2/25
     * Time: 16:40
     */
    class FollowModel extends BaseModel
    {
        var $table  = 'follows';
        var $prikey = 'id';
        var $_name  = 'follows';
		
	private function getTable ()
	{
		return DB_PREFIX_NEW . 'follows';
	}
        /**
         * 关注
         *
         * @param $user_id      我
         * @param $follow_id    关注谁
         *
         * @return bool|int
         */
        public function addFollow ( $user_id, $follow_id )
        {
            $sql  = sprintf ( "INSERT INTO %s ( user_id, follow_id ) VALUES ( %u, %u )", $this->getTable (), $user_id, $follow_id );
            $flag = $this->query ( $sql );
            if ( $flag )
            {
                return mysql_insert_id ();//获取最后插入的id
            }
            else
            {
                return $flag;
            }
        }

        /**
         * 获取我的粉丝ID
         *
         * @param     $user_id
         * @param int $offset
         * @param int $size
         *
         * @return mixed
         */
        public function getFollowIds ( $user_id, $offset = 0, $size = 10 )
        {
            $sql = sprintf ( 'SELECT `follow_id` FROM %s WHERE `user_id`=%u ORDER BY `id` DESC LIMIT %u, %u', $this->getTable (), $user_id, $offset, $size );
	    foreach ( $this->getAll ( $sql ) as $temp )$ids [] = $temp ['follow_id'];
            return $ids;
        }

        /**
         * 取消关注
         *
         * @param $user_id      我
         * @param $follow_id    取消关注谁
         *
         * @return bool
         */
        public function unFollow ( $user_id, $follow_id )
        {
            $sql  = sprintf ( "DELETE FROM %s WHERE `user_id`=%u AND `follow_id`=%u", $this->getTable (), $user_id, $follow_id );
            return $this->query($sql);
        }

        /**
         * 检查是否已经关注
         *
         * @param $user_id      我
         * @param $follow_id    关注谁
         *
         * @return bool
         */
        public function isFollow ( $user_id, $follow_id )
        {
            $sql = sprintf ( 'SELECT COUNT(`id`) AS `total` FROM %s WHERE `user_id`=%u AND `follow_id`=%u', $this->getTable (), $user_id, $follow_id );

            return $this->getOne ( $sql ) > 0;
        }

        /**
         * @author mingyang.sun
         * @date 2016-02-25
         * @param $user_id
         * @param $follow_ids
         *
         * @return mixed
         */
        public function getFollowByFollowId ( $user_id, $follow_ids )
        {
            $ids=array();
            $sql = sprintf (  'SELECT `follow_id` FROM %s WHERE `user_id`=%u AND `follow_id` IN ( %s )', $this->getTable (),$user_id,implode ( ',', $follow_ids )  );
            foreach ( $this->getAll ( $sql ) as $temp )$ids [] = $temp ['follow_id'];
            return $ids;

        }
    }